package utils
{
	import flash.utils.ByteArray;

	public class CRC16
	{
		
		public function CRC16()
		{
			
			
			
			
		}
		
		public function toString1(hex:String):String {
			var a:ByteArray = toArray(hex);
			return a.readUTFBytes(a.length);
		}
		
		
		/**
		 * 
		 * @param str
		 * @return a hex string encoded from the UTF-8 string str
		 * 
		 */
		public static function fromString(str:String, colons:Boolean=false):String {
			var a:ByteArray = new ByteArray;
			a.writeUTFBytes(str);
			return fromArray(a, colons);
		}
		
		public static function toArray(hex:String):ByteArray {
			hex = hex.replace(/\s|:/gm,'');
			var a:ByteArray = new ByteArray;
			if (hex.length&1==1) hex="0"+hex;
			for (var i:uint=0;i<hex.length;i+=2) {
				a[i/2] = parseInt(hex.substr(i,2),16);
			}
			return a;
		}
		
		public static function fromArray(array:ByteArray, colons:Boolean=false):String {
			var s:String = "";
			for (var i:uint=0;i<array.length;i++) {
				s+=("0"+array[i].toString(16)).substr(-2,2);
				if (colons) {
					if (i<array.length-1) s+=":";
				}
			}
			return s;
		}
		
		public static function  getCrc16Code( crcString:String):String  
		{  
			
			// 转换成字节数组  
			var creBytes:ByteArray =toArray(crcString);  
			// 开始crc16校验码计算  
			var  crc16:CRC16Util = new CRC16Util();  
			crc16.reset();  
			crc16.update(creBytes);  
			var crc:int = crc16.getCrcValue();  
			// 16进制的CRC码  
			var crcCode:String = crc.toString(16);  
			// 补足到4位  
			if (crcCode.length < 4)  
			{  
				crcCode = NumberTool.fullZeroWidthPosition(crcCode,4,"l");
				
			}  
			return crcCode;  
		}  
		
		
		
		
		
	}
	
	
}

